/**
 * 全站路由配置
 *
 * 建议:
 * 1. 代码中路由统一使用name属性跳转(不使用path属性)
 */
import Vue from 'vue'
import Router from 'vue-router'
import http from '@/utils/httpRequest'
import { isURL } from '@/utils/validate'
import { clearLoginInfo } from '@/utils'

Vue.use(Router)

// 开发环境不使用懒加载, 因为懒加载页面太多的话会造成webpack热更新太慢, 所以只有生产环境使用懒加载
const _import = require('./import-' + process.env.NODE_ENV)

// 全局路由(无需嵌套上左右整体布局)
const globalRoutes = [
  { path: '/404', component: _import('common/404'), name: '404', meta: { title: '404未找到' } },
  { path: '/login', component: _import('common/login'), name: 'login', meta: { title: '登录' } }
]

// 主入口路由(需嵌套上左右整体布局)
const mainRoutes = {
  path: '/',
  component: _import('main'),
  name: 'main',
  redirect: { name: 'home' },
  meta: { title: '主入口整体布局' },
  children: [
    // 通过meta对象设置路由展示方式
    // 1. isTab: 是否通过tab展示内容, true: 是, false: 否
    // 2. iframeUrl: 是否通过iframe嵌套展示内容, '以http[s]://开头': 是, '': 否
    // 提示: 如需要通过iframe嵌套展示内容, 但不通过tab打开, 请自行创建组件使用iframe处理!
    { path: '/home', component: _import('common/home'), name: 'home', meta: { title: '首页' } },
    { path: '/theme', component: _import('common/theme'), name: 'theme', meta: { title: '主题' } },
    /* { path: '/demo-echarts', component: _import('demo/echarts'), name: 'demo-echarts', meta: { title: 'demo-echarts', isTab: true } },
    { path: '/demo-ueditor', component: _import('demo/ueditor'), name: 'demo-ueditor', meta: { title: 'demo-ueditor', isTab: true } }, */
    { path: '/sys/sysitemdetails', component: _import('modules/sys/sysitemdetails'), name: 'sysitemdetails', meta: { title: '字典明细', isTab: false } },
    { path: '/bid/supplier-edit', component: _import('modules/bid/supplier-edit'), name: 'supplier-edit', meta: { title: '供应商信息', isTab: false } },
    { path: '/bid/project-edit', component: _import('modules/bid/project-edit'), name: 'project-edit', meta: { title: '项目信息', isTab: false } },
    { path: '/bid/project-competitive-edit', component: _import('modules/bid/project-competitive-edit'), name: 'project-competitive-edit', meta: { title: '询比价信息', isTab: false } },
    { path: '/bid/project-centralized-order-edit', component: _import('modules/bid/project-centralized-order-edit'), name: 'project-centralized-order-edit', meta: { title: '集中采购信息', isTab: false } },
    { path: '/bid/project-odd-edit', component: _import('modules/bid/project-odd-edit'), name: 'project-odd-edit', meta: { title: '零星采购信息', isTab: false } },
    { path: '/bid/project-competitive-invite', component: _import('modules/bid/project-competitive-invite'), name: 'project-competitive-invite', meta: { title: '投标邀请编辑', isTab: false } },
    { path: '/bid/project-dashboard', component: _import('modules/bid/project-dashboard'), name: 'project-dashboard', meta: { title: '项目主控台', isTab: false } },
    { path: '/bid/project-competitive-dashboard', component: _import('modules/bid/project-competitive-dashboard'), name: 'project-competitive-dashboard', meta: { title: '询价项目主控台', isTab: false } },
    { path: '/bid/announcement-edit', component: _import('modules/bid/announcement-edit'), name: 'announcement-edit', meta: { title: '招标公告编辑', isTab: false } },
    { path: '/bid/bider-pre-apply', component: _import('modules/bid/bider-pre-apply'), name: 'bider-pre-apply', meta: { title: '资格预审文件', isTab: false } },
    { path: '/bid/bid-open-secret', component: _import('modules/bid/bid-open-secret'), name: 'bid-open-secret', meta: { title: '解密开启', isTab: false } },
    { path: '/bid/question-add-edit', component: _import('modules/bid/question-add-edit'), name: 'question-add-edit', meta: { title: '新增提问', isTab: true } },

    { path: '/bid/enrol-add-edit', component: _import('modules/bid/enrol-add-edit'), name: 'enrol-add-edit', meta: { title: '报名申请', isTab: true } },

    { path: '/bid/my-project-console', component: _import('modules/bid/my-project-console'), name: 'my-project-console', meta: { title: '项目控制台', isTab: true } },

    { path: '/bid/question-list', component: _import('modules/bid/question-list'), name: 'question-list', meta: { title: '查询澄清问题', isTab: true } },

    { path: '/bid/road-notice', component: _import('modules/bid/road-notice'), name: 'road-notice', meta: { title: '路勘通知', isTab: true } },

    { path: '/bid/my-road-confirm', component: _import('modules/bid/my-road-confirm'), name: 'my-road-confirm', meta: { title: '路勘通知确认', isTab: true } },

    { path: '/bid/road-notice-add-edit', component: _import('modules/bid/road-notice-add-edit'), name: 'road-notice-add-edit', meta: { title: '编辑路勘通知', isTab: true } },

    { path: '/bid/road-log', component: _import('modules/bid/road-log'), name: 'road-log', meta: { title: '路勘记录', isTab: true } },

    { path: '/bid/road-log-add-edit', component: _import('modules/bid/road-log-add-edit'), name: 'road-log-add-edit', meta: { title: '编辑路勘记录', isTab: true } },

    { path: '/bid/my-bidding-confirm', component: _import('modules/bid/my-bidding-confirm'), name: 'my-bidding-confirm', meta: { title: '投标确认函', isTab: true } },

    { path: '/bid/my-bidding-submit', component: _import('modules/bid/my-bidding-submit'), name: 'my-bidding-submit', meta: { title: '递交投标文件', isTab: true } },

    { path: '/bid/bidding-list', component: _import('modules/bid/bidding-list'), name: 'bidding-list', meta: { title: '投标信息查看', isTab: true } },

    { path: '/bid/my-deposit-submit', component: _import('modules/bid/my-deposit-submit'), name: 'my-deposit-submit', meta: { title: '保证金信息递交', isTab: true } },

    { path: '/bid/deposit-list', component: _import('modules/bid/deposit-list'), name: 'deposit-list', meta: { title: '保证金管理', isTab: true } },
    { path: '/bid/depositrefund-list', component: _import('modules/bid/depositrefund-list'), name: 'depositrefund-list', meta: { title: '保证金退款记录', isTab: true } },
    { path: '/expert/expertgroup-edit', component: _import('modules/expert/expertgroup-edit'), name: 'expertgroup-edit', meta: { title: '委员会组建', isTab: false } },

    { path: '/bid/service-fee', component: _import('modules/bid/service-fee'), name: 'service-fee', meta: { title: '服务费管理', isTab: true } },

    { path: '/bid/evaluation-prepare', component: _import('modules/bid/evaluation-prepare'), name: 'evaluation-prepare', meta: { title: '评标准备', isTab: true } },

    { path: '/bid/evaluation-manage', component: _import('modules/bid/evaluation-manage'), name: 'evaluation-manage', meta: { title: '评标管理', isTab: true } },

    { path: '/bid/evaluation-confirm', component: _import('modules/bid/evaluation-confirm'), name: 'evaluation-confirm', meta: { title: '确定中标人', isTab: true } },

    { path: '/bid/evaluation-notice', component: _import('modules/bid/evaluation-notice'), name: 'evaluation-notice', meta: { title: '中标公示', isTab: true } },

    { path: '/bid/evaluation-reconfirm', component: _import('modules/bid/evaluation-reconfirm'), name: 'evaluation-reconfirm', meta: { title: '重新确定中标人', isTab: true } },

    { path: '/bid/evaluation-notification', component: _import('modules/bid/evaluation-notification'), name: 'evaluation-notification', meta: { title: '中标通知书处理', isTab: true } },

    { path: '/bid/evaluation-notification-update', component: _import('modules/bid/evaluation-notification-update'), name: 'evaluation-notification-update', meta: { title: '中标通知书编辑', isTab: true } }
  ],
  beforeEnter (to, from, next) {
    let token = Vue.cookie.get('token')
    if (!token || !/\S/.test(token)) {
      clearLoginInfo()
      next({ name: 'login' })
    }
    next()
  }
}

const router = new Router({
  mode: 'hash',
  scrollBehavior: () => ({ y: 0 }),
  isAddDynamicMenuRoutes: false, // 是否已经添加动态(菜单)路由
  routes: globalRoutes.concat(mainRoutes)
})

router.beforeEach((to, from, next) => {
  // 添加动态(菜单)路由
  // 1. 已经添加 or 全局路由, 直接访问
  // 2. 获取菜单列表, 添加并保存本地存储
  if (router.options.isAddDynamicMenuRoutes || fnCurrentRouteType(to, globalRoutes) === 'global') {
    next()
  } else {
    http({
      url: http.adornUrl('/sys/menu/nav'),
      method: 'get',
      params: http.adornParams()
    }).then(({data}) => {
      if (data && data.code === 0) {
        fnAddDynamicMenuRoutes(data.menuList)
        router.options.isAddDynamicMenuRoutes = true
        sessionStorage.setItem('menuList', JSON.stringify(data.menuList || '[]'))
        sessionStorage.setItem('permissions', JSON.stringify(data.permissions || '[]'))
        next({ ...to, replace: true })
      } else {
        sessionStorage.setItem('menuList', '[]')
        sessionStorage.setItem('permissions', '[]')
        next()
      }
    }).catch((e) => {
      console.log(`%c${e} 请求菜单列表和权限失败，跳转至登录页！！`, 'color:blue')
      router.push({ name: 'login' })
    })
  }
})

/**
 * 判断当前路由类型, global: 全局路由, main: 主入口路由
 * @param {*} route 当前路由
 */
function fnCurrentRouteType (route, globalRoutes = []) {
  var temp = []
  for (var i = 0; i < globalRoutes.length; i++) {
    if (route.path === globalRoutes[i].path) {
      return 'global'
    } else if (globalRoutes[i].children && globalRoutes[i].children.length >= 1) {
      temp = temp.concat(globalRoutes[i].children)
    }
  }
  return temp.length >= 1 ? fnCurrentRouteType(route, temp) : 'main'
}

/**
 * 添加动态(菜单)路由
 * @param {*} menuList 菜单列表
 * @param {*} routes 递归创建的动态(菜单)路由
 */
function fnAddDynamicMenuRoutes (menuList = [], routes = []) {
  var temp = []
  for (var i = 0; i < menuList.length; i++) {
    if (menuList[i].list && menuList[i].list.length >= 1) {
      temp = temp.concat(menuList[i].list)
    } else if (menuList[i].url && /\S/.test(menuList[i].url)) {
      menuList[i].url = menuList[i].url.replace(/^\//, '')
      var route = {
        path: menuList[i].url.replace('/', '-'),
        component: null,
        name: menuList[i].url.replace('/', '-'),
        meta: {
          menuId: menuList[i].menuId,
          title: menuList[i].name,
          isDynamic: true,
          isTab: true,
          iframeUrl: ''
        }
      }
      // url以http[s]://开头, 通过iframe展示
      if (isURL(menuList[i].url)) {
        route['path'] = `i-${menuList[i].menuId}`
        route['name'] = `i-${menuList[i].menuId}`
        route['meta']['iframeUrl'] = menuList[i].url
      } else {
        try {
          route['component'] = _import(`modules/${menuList[i].url}`) || null
        } catch (e) {}
      }
      routes.push(route)
    }
  }
  if (temp.length >= 1) {
    fnAddDynamicMenuRoutes(temp, routes)
  } else {
    mainRoutes.name = 'main-dynamic'
    mainRoutes.children = routes
    router.addRoutes([
      mainRoutes,
      { path: '*', redirect: { name: '404' } }
    ])
    sessionStorage.setItem('dynamicMenuRoutes', JSON.stringify(mainRoutes.children || '[]'))
    console.log('\n')
    console.log('%c!<-------------------- 动态(菜单)路由 s -------------------->', 'color:blue')
    console.log(mainRoutes.children)
    console.log('%c!<-------------------- 动态(菜单)路由 e -------------------->', 'color:blue')
  }
}

export default router
